import FieldsUtils from '@/utils/fields';
import { BetaSchemaForm, DrawerForm, ProFormInstance } from '@ant-design/pro-components';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { DetailFormRef, FormComponentProps } from './types';

const XcDetailForm = forwardRef<DetailFormRef, FormComponentProps>((props, ref) => {
  const formRef = useRef<ProFormInstance>();

  const [isOpen, setIsOpen] = useState(false);

  /**
   * 设置表单数据值
   */
  const setFieldsValue = (values: any) => {
    formRef.current?.resetFields();
    formRef.current?.setFieldsValue(values);
  };

  /**
   * 重置表单字段
   */
  const resetFields = () => {
    formRef.current?.resetFields();
  };

  const show = (values: any) => {
    let _values = FieldsUtils.handleImageDisplay(props.columns, values);
    setFieldsValue(_values);
    setIsOpen(true);
  };

  useImperativeHandle(ref, () => ({
    setFieldsValue,
    resetFields,
    show,
  }));

  /**
   * 处理抽屉关闭
   */
  const handleOpenChange = (open: boolean) => {
    setIsOpen(open);
    if (!open && props.onCancel) {
      props.onCancel();
    }
  };

  const columns = props.columns;
  return (
    <DrawerForm
      open={isOpen}
      onOpenChange={handleOpenChange}
      title={props.title}
      onFinish={props.onFinish}
      formRef={formRef}
      width="60vw"
      readonly={true}
      drawerProps={{ forceRender: true }}
      submitter={{
        searchConfig: {
          resetText: '关闭',
        },
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
      }}
      grid
      layout="horizontal"
      {...props}
    >
      {props.children}
      <BetaSchemaForm layoutType="Embed" columns={columns} />
    </DrawerForm>
  );
});

export default XcDetailForm;
